package com.fbs.service.impl;

import com.fbs.dao.UserDao;


import com.fbs.entity.User;
import com.fbs.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;


@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public User findById(Integer id) {
        ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        Object o = forValue.get("user::" + id);
        if (o!=null){
            return (User) o;
        }
        User user = userDao.selectById(id);
        if (user!=null){
            forValue.set("user::"+id,user,3600, TimeUnit.SECONDS);

        }
        return user;
    }

    @Override
    public Integer delById(Integer id) {
        redisTemplate.delete("user::"+id);
        int i = userDao.deleteById(id);
        return i;
    }

    @Override
    public User save(User user) {
        userDao.insert(user);
        return user;
    }

    @Override
    public User update(User user) {
        userDao.updateById(user);
        ValueOperations<String, Object> forValue = redisTemplate.opsForValue();
        forValue.set("user::"+user.getId(),user,3600,TimeUnit.SECONDS);
        return user;

    }
}
